package com.paic.common.middleware.util

import org.apache.hadoop.hbase.client.{Connection, ConnectionFactory}
import org.apache.hadoop.hbase.{HBaseConfiguration, HColumnDescriptor, HTableDescriptor, TableName}

/**
  * Created by Jerry on 2018/5/9.
  *
  */
object HbaseUtils {
  /**
   * get connection from conf,hbase-site.xml must in project conf
   */
  def getConnection(): Connection = {
    val conf = HBaseConfiguration.create()
    val connection = ConnectionFactory.createConnection(conf)
    connection
  }
  /**
   * list tables from hbase,return a Array with HTableDescriptor
   */
  def listTables(): Array[HTableDescriptor] = {
    val connection = getConnection;
    val admin = connection.getAdmin()
    val hbaseTablesArray = admin.listTables()
    hbaseTablesArray
  }

  def createTableOnHBase(tableName: String, columnFamily: List[String], dropOrNot: Boolean): String = {
    var resultInfo = ""
    if ("".equals(tableName)) {
      resultInfo = "tableName is empty!"
      return resultInfo
    } else if ("".equals(columnFamily.isEmpty)) {
      resultInfo = "columnFamily is empty!"
      return resultInfo
    }
    val connection = getConnection;
    val admin = connection.getAdmin
    val tableNameDescription = TableName.valueOf(tableName)
    val tableDescription = new HTableDescriptor(tableNameDescription)
    for (tempFamily <- columnFamily) {
      tableDescription.addFamily(new HColumnDescriptor(tempFamily.getBytes))
    }
    if (admin.tableExists(tableNameDescription) && dropOrNot) {
      admin.disableTable(tableNameDescription)
      admin.deleteTable(tableNameDescription)
      admin.createTable(tableDescription)
      if (admin.tableExists(tableNameDescription)) {
        resultInfo = "true"
        return resultInfo
      } else {
        resultInfo = "false"
        return resultInfo
      }
    } else {
      resultInfo = "table exist,not drop ,create table error";
      return resultInfo
    }
  }

  def getDataByRowKeyAndColumnFamily(tableName: String, rowKey: String, columnFamilys: List[String]): String = {
    var resultInfo = ""
    if ("".equals(tableName)) {
      resultInfo = "tableName is empty!"
      return resultInfo
    }
    ""
  }

  def putData(tableName: String, rowKey: String, dataList: Map[String, String]): String = {
    var resultInfo = ""
    if ("".equals(tableName)) {
      resultInfo = "tableName is empty!"
      return resultInfo
    } else if ("".equals(rowKey)) {
      resultInfo = "rowKey is empty!"
      return resultInfo
    }
    ""
  }

  def main(args: Array[String]): Unit = {
    val tables = listTables();
    tables.foreach(println)
    println("dfasdf:" + createTableOnHBase("cyb", List("a", "b", "c"), false))
  }
}
